package com.sam.stream;

import java.io.IOException;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.net.ServerSocket;
import java.net.Socket;

import com.sam.DataStream;


public class NetworkStream extends Thread {
 
    public static final int SERVERPORT = 8080;
    protected boolean running = false;
    protected ObjectOutputStream oos;
    protected ObjectInputStream ois;
    private OnMessageReceived messageListener;
    


	public NetworkStream(OnMessageReceived messageListener)
	{
		this.messageListener = messageListener;

	}

	public ObjectInputStream getOIS()
	{
		return ois;
	}

	public void sendMessage(DataStream data)
	{

		if (oos != null)
		{
			System.out.println("oos is not null");
			try
			{
				oos.writeObject(data);
				oos.flush();
				System.out.println("send msg " + data.getmessage());
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@Override
	public void run()
	{
		super.run();

		running = true;

		try
		{
			System.out.println("S: Connecting...");

			// create a server socket. A server socket waits for requests to
			// come in over the network.
			@SuppressWarnings("resource")
			ServerSocket serverSocket = new ServerSocket(SERVERPORT);

			while (true)
			{
				// create client socket... the method accept() listens for a
				// connection to be made to this socket and accepts it.
				Socket client = serverSocket.accept();
				System.out.println("S: Receiving...");

				try
				{

					// sends the message to the client
					// mOut = new PrintWriter(new BufferedWriter(new
					// OutputStreamWriter(client.getOutputStream())), true);

					oos = new ObjectOutputStream(client.getOutputStream());
					oos.writeObject(new DataStream("Snone", null, null));

					// read the message received from client
					// BufferedReader in = new BufferedReader(new
					// InputStreamReader(client.getInputStream()));
					ois = new ObjectInputStream(client.getInputStream());

					// in this while we wait to receive messages from client
					// (it's an infinite loop)
					// this while it's like a listener for messages
					while (running)
					{
						// String message = in.readLine();
						if (ois != null)
						{
							DataStream data = (DataStream) ois.readObject();

							if (data != null && messageListener != null)
							{
								messageListener.messageReceived(data);
							}
						}
					}

				}
				catch (Exception e)
				{
					System.out.println("S: Error");
					e.printStackTrace();
				}
				finally
				{
					client.close();
					System.out.println("S: Done.");
				}
			}

		}
		catch (Exception e)
		{
			System.out.println("S: Error");
			e.printStackTrace();
		}

	}

	public interface OnMessageReceived
	{
		public void messageReceived(DataStream data);
	}

}
